import axios from 'axios'
import router from '../router/index'
import { Notification, MessageBox, Message } from 'element-ui'

const instance = axios.create({
  //baseURL:'http://zlh1nj9x.shenzhuo.vip:11175',
  //baseURL:'http://yifei.free.idcfengye.com',
  baseURL: 'http://47.108.218.32:8989/api',
  timeout: 10000,
})

export default instance

axios.interceptors.request.use(config => {
  if (window.sessionStorage.getItem('tokenStr')) {
    config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr')
  }
  return config
}, error => {

})

axios.interceptors.response.use(res => {
  if (res.headers['content-type'] === 'application/octet-stream' || res.config.url === '/api/json/provinces.json') {
    return res
  }
  if (res.data.code === 999 || res.data.code === 2003 || res.data.code === 2008 || res.data.code === 2005
    || res.data.code === 2010 || res.data.code === 2501 || res.data.code === 3001
    || res.data.code === 3007 || res.data.code === 3008 || res.data.code === 3009) {
    Message.error(res.data.message)
  } else if (res.data.code === 2001 || res.data.code === 2004) {
    //登陆过期或密码过期
    logout()
    window.sessionStorage.setItem('logout', '0')
  } else if (res.data.code === 2009) {
    //被挤下线
    MessageBox.confirm(res.data.message, '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '退出',
        type: 'warning'
      }
    ).then(action => {
      window.sessionStorage.setItem('logout', '0')
      if (action === 'confirm') {
        window.sessionStorage.removeItem('tokenStr')
        router.push('/login')
      }
    }).catch(err => {
      window.sessionStorage.setItem('logout', '0')
      if (err === 'cancel') {
        window.sessionStorage.removeItem('tokenStr')
        router.push('/login')
      }
    })
  } else if (res.data.code === 200) {
    return res
  }
}, error => {
  return Promise.reject(error)
})

const logout = () => {
  if (window.sessionStorage.getItem('logout') === '1') {
    MessageBox.confirm('登录状态或密码已过期，请重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(action => {
      if (action === 'confirm') {
        window.sessionStorage.removeItem('tokenStr')
        router.push('/login')
      }
    }).catch(err => {
      if (err === 'cancel') {
        window.sessionStorage.setItem('logout', '1')
      }
    })
  }
}

export const postRequest = (url, data) => {
  return axios({
    url: `${url}`,
    method: 'post',
    data: data
  })
}

export const getRequest = (url, data) => {
  return axios({
    url: `${url}`,
    method: 'get',
    data: data
  })
}
